package com.example.demo.pdfbox.processor;

import com.example.demo.pdfbox.common.FontClass;
import com.example.demo.pdfbox.common.PdfProcessElement;
import com.example.demo.pdfbox.common.Position;
import com.example.demo.pdfbox.common.function.ElementProcess;
import com.example.demo.pdfbox.tabel.PdfElement;
import com.example.demo.pdfbox.tabel.concrete.PdfLine;
import com.example.demo.pdfbox.tabel.concrete.PdfPicture;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import java.io.IOException;

public class PdfPictureProcessor implements ElementProcess {
    @Override
    public int process(PdfProcessElement pdfProcessElement) throws IOException {
        int pageNum = 0;
        PdfElement element = pdfProcessElement.element;
        FontClass fontClass = pdfProcessElement.fontClass;
        Position position = pdfProcessElement.position;
        PDDocument document = pdfProcessElement.document;
        PDPageContentStream contentStream = pdfProcessElement.contentStream;


        PdfPicture picture = (PdfPicture) element;

        position.startY -= element.getY();
        position.startX += element.getX();

        if (position.startY - picture.getHeight() <= position.margin.getMarginFoot()) {
            PDPage page = new PDPage(position.rectangle);
            document.addPage(page);
            position.startY = page.getMediaBox().getHeight() - position.margin.getMarginHead() - element.getY() - picture.getHeight();
            contentStream.close();
            contentStream = new PDPageContentStream(document, page);
            pageNum++;
        }

        final PDImageXObject image = PDImageXObject.createFromByteArray(document, picture.getImage(), "picture");
        contentStream.drawImage(image, position.startX , position.startY , picture.getWidth(), picture.getHeight());

        pdfProcessElement.element = element;
        pdfProcessElement.fontClass = fontClass;
        pdfProcessElement.position = position;
        pdfProcessElement.document = document;
        pdfProcessElement.contentStream = contentStream;
        return pageNum;

    }
}
